/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.modules.search.hichao;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.log.Logger;
import com.koorz.modules.search.SimpleHttpClient;
import com.koorz.modules.search.UrlWrapper;

/**
 * 功能描述：获取导航页数据任务
 * 作        者：尹东东 
 * 创建时间：2013-5-27 下午3:58:21
 * 版  本  号：1.0
 */
public class NaviTask implements Runnable{
	protected final Logger logger = Logger.getLogger(getClass());
	
	@Override
	public void run() {
		logger.debug("进入 NaviTask");
		SimpleHttpClient client = new SimpleHttpClient();
		HichaoParser parser = HichaoParser.getInstance();
		while (true) {
			UrlWrapper navi = parser.getMenus();
			if(navi != null){
				String result = client.get(navi.getUrl(),parser.getCookie());
				if(StringUtils.isEmpty(result)){
					continue;
				}
				JSONArray jsonArray = null;
				try {
					JSONObject json = JSON.parseObject(result);
					JSONObject data = json.getJSONObject("data");
					jsonArray = data.getJSONArray("content");
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("NaviTask 获取导航数据失败！"+navi.getUrl(), e);
					continue;
				}
				if(jsonArray != null){
					for(int i=0;i<jsonArray.size();i++){
						JSONObject content = jsonArray.getJSONObject(i);
						String url = "http://www.hichao.com/api/starInfo?star_id="+content.getString("id");
//						menus.add(new UrlWrapper("http://www.hichao.com/api/starCategory?page="
//								+ i + "&query=" + style + "&more=" + k,categoryName,labelGroupName,style,category.getStr("id"),labelGroup.getStr("id"),label.getStr("id")));
						logger.debug("添加到 url："+url+",当前大小"+parser.navis.size());
						parser.addNavi(new UrlWrapper(url,navi.getMenu(),navi.getLabelGroup(),navi.getLabel(),navi.getCategoryId(),navi.getLabelGroupId(),navi.getLabelId()));
					}
				}else {
					continue;
				}
			}else {
				logger.debug("isComplate");
				parser.setMaxCount();
				break;
			}
		}
		client.close();
	}

}
